package leetcode;

import util.Tree;
import util.TreeNode;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0110.java
 * @Author : WangRuoyu
 * @Date 2023/10/22 20:07
 */

public class Q0110 {
    private static int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int lhight = dfs(node.left);
        int rhight = dfs(node.right);
        int diff = Math.abs(lhight - rhight);
        if (lhight == -1 || rhight == -1 || diff > 1) {
            return -1;
        } else {
            return Math.max(lhight, rhight) + 1;
        }
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (dfs(root) == -1) {
            return false;
        } else {
            return true;
        }
    }

    public static void main(String[] args) {
        Q0110 sl = new Q0110();
        String[] tree = {"3", "9", null, null, "20", "15", null, null, "7", null, null};
        TreeNode root = Tree.createTreeByPreorder(tree);
        System.out.println(sl.isBalanced(root));
    }
}